//
//  Stack.c
//  栈
//
//  Created by 卜绎皓 on 2022/6/25.
//

#include "Stack.h"

void StackInit(ST* ps)
{
    assert(ps);
    //初始化
    ps->a = NULL;
    ps->top = 0;
    ps->capacicy = 0;
}
void StackPush(ST* ps, STDatatype x)
{
    assert(ps);
    //检查空间，满了就增容
    if (ps->top == ps->capacicy)
    {
        //第一次开辟空间容量为4，其它次容量为当前容量*2
        int newcapacity = ps->capacicy == 0 ? 4 : ps->capacicy * 2;
        //第一次开辟空间，a指向空，realloc的效果同malloc
        STDatatype* tmp = realloc(ps->a, sizeof(STDatatype) * newcapacity);
        //检查realloc
            //realloc失败
        if (tmp == NULL)
        {
            printf("realloc fail\n");
            exit(-1);
        }
            //realloc成功
        ps->a = tmp;
        ps->capacicy = newcapacity;
    }
    //插入数据
    ps->a[ps->top] = x;
    ps->top++;
}
bool StackEmpty(ST* ps)
{
    assert(ps);
    //等于0是真，否则为假
    return ps->top == 0;
}
void StackPop(ST* ps)
{
    assert(ps);
    //删除的话得保证指向的空间不为空
    assert(!StackEmpty(ps));
    //删除
    --ps->top;
}
int StackSize(ST* ps)
{
    assert(ps);
    //此时的top就是长度
    return ps->top;
}
STDatatype StackTop(ST* ps)
{
    assert(ps);
    //找栈顶的话得保证指向的空间不为空
    assert(!StackEmpty(ps));
    //此时的top-1就是栈顶数据
    return ps->a[ps->top - 1];
}
void StackDestory(ST* ps)
{
    assert(ps);
    //a为真代表它指向动态开辟的空间
    if (ps->a)
    {
        free(ps->a);
    }
    ps->a = NULL;
    ps->top = 0;
    ps->capacicy = 0;
}

